package com.ambow.shop.service.impl;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import com.ambow.shop.dao.ProductDao;
import com.ambow.shop.dao.impl.ProductDaoJdbcImpl;
import com.ambow.shop.domain.Product;
import com.ambow.shop.service.ProductService;
import com.ambow.shop.util.JdbcUtils;
import com.ambow.shop.util.Page;

/**
 * 产品业务模型实现。
 * 
 * @author chunw
 *
 */
public class ProductServiceImpl implements ProductService {

	private ProductDao productDao = new ProductDaoJdbcImpl();

	@Override
	public boolean addProduct(Product product) {
		try (Connection conn = JdbcUtils.getConnection();) {
			return productDao.add(product) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean deleteProduct(Integer id) {
		try (Connection conn = JdbcUtils.getConnection();) {
			return productDao.delete(id) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public boolean updateProduct(Product product) {
		try (Connection conn = JdbcUtils.getConnection();) {
			return productDao.update(product) == 1;
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public Product getProduct(Integer productId) {
		try (Connection conn = JdbcUtils.getConnection();) {
			return productDao.get(productId);
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public Page<Product> findProducts(int currentPage, int pageSize) {
		try (Connection conn = JdbcUtils.getConnection();) {
			Long totalRows = productDao.getTotalRows();
			List<Product> products = productDao.list(pageSize * (currentPage - 1), pageSize);
			Page<Product> page = new Page<Product>(currentPage, products, totalRows, pageSize);
			return page;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		}
	}

}